#! /usr/bin/env python3

from pathlib import Path, PurePath
import re
import hashlib
import tarfile

cwd = Path.cwd()
subproject_dir = cwd / '3rd'
wrap_patches_dir = subproject_dir / 'wrap_patches'

def process_wrap_patches():
    for p in wrap_patches_dir.iterdir():
        if not p.is_dir(): continue
        tf = tarfile.open(str(subproject_dir / (p.name + '_patch.tar')), 'w')
        tf.add(str(p), arcname=p.name)
        tf.close()

def process_wrap_templates():
    for tf in subproject_dir.glob('*.wrap.tmpl'):
        wf = subproject_dir / PurePath(tf).stem
        with wf.open(mode='w') as w:
            with tf.open(mode='r') as t:
                d = ''
                while True:
                    l = t.readline()
                    if l == '': break;
                    if re.match('^patch_filename', l):
                        h = hashlib.new('sha256')
                        bs = h.block_size
                        pf = re.split('=', l)[1].strip()
                        with (subproject_dir / pf).open(mode='rb') as f:
                            while True:
                                b = f.read(bs)
                                if not b: break
                                h.update(b)
                        d = h.hexdigest()
                    l = re.sub('%top%', subproject_dir.as_uri(), l)
                    if re.match('^patch_hash', l) and d == '':
                        print('%s: patch_hash must follow patch_filename\n' % t.name)
                    l = re.sub('%patch_hash%', d, l)
                    w.write(l)

process_wrap_patches()
process_wrap_templates()
